package library_system.com;

import library_system.Util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * @author haomin
 * @date 2022/04/05 20:50
 **/
public class BorrowBookCommand {
    public static void main(String[] args) throws SQLException {
        // 1. 登录
        // 1.1 证明你是你
        // 1.2 权限（角色）
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();

        // select 判断是否存在该用户
        int currentRid;
        try (Connection c = DBUtil.connection()) {
            String sql = "select rid from readers where name = ?";
            try (PreparedStatement ps = c.prepareStatement(sql)) {
                ps.setString(1, username);

                try (ResultSet rs = ps.executeQuery()) {
                    if (!rs.next()) {
                        System.out.println("登录失败！");
                        return;
                    } else {
                        currentRid = rs.getInt("rid");
                        System.out.println("登录成功");
                        System.out.println();
                    }
                }
            }
        }

        System.out.print("请输入书名: ");
        String bookName = scanner.nextLine();
        // select 书籍有没有 && count > 0
        // update books + insert records
        int bid;
        int count;
        try (Connection c = DBUtil.connection()) {
            String sql = "select bid ,stock from books where name = ?";
            try (PreparedStatement ps = c.prepareStatement(sql)) {
                ps.setString(1, bookName);

                try (ResultSet rs = ps.executeQuery()) {
                    if (!rs.next()) {
                        System.out.println("查无此书！");
                        return;
                    } else {
                        bid = rs.getInt("bid");
                        count = rs.getInt("stock");
                    }
                    if (count == 0) {
                        System.out.println("书被借空了");
                        return;
                    }
                }
            }
        }

        // 借书操作
        try (Connection c = DBUtil.connection()) {
            String sql = "update books set stock = stock - 1 where bid = ?";
            try (PreparedStatement ps = c.prepareStatement(sql)) {
                ps.setInt(1, bid);

                ps.executeUpdate();
            }
        }
        try (Connection c = DBUtil.connection()) {
            String sql = "insert into records (rid, bid) values (?, ?)";
            try (PreparedStatement ps = c.prepareStatement(sql)) {
                ps.setInt(1, currentRid);
                ps.setInt(2, bid);

                ps.executeUpdate();
            }
        }
        System.out.println("借书成功！");
    }
}